function [ conn, times ] = osl_conn_hilbert_plv( S )

% PLV: Measuring Phase Synchrony in Brain Signals. Jean-Philippe Lachaux et al, HBM 1999
    
try tmp=S.dat; catch, error('S.dat not set'); end;
try tmp=S.dat_seed; catch, error('S.dat_seed not set'); end;
try tmp=S.times_in; catch, error('S.times_in'); end;
try tmp=S.time_range; catch, error('S.time_range'); end;
try tmp=S.baseline_timespan; catch, error('S.baseline_timespan'); end;
try tmp=S.bc; catch, S.bc=0; end;
   
baseline_time_indices=S.times_in<S.baseline_timespan(2) & S.times_in>S.baseline_timespan(1);

time_indices=S.times_in>S.time_range(1) & S.times_in<S.time_range(2);

if(sum(baseline_time_indices)>0),
    conn=zeros(size(S.dat,1),2);
    times(1) = mean(S.times_in(baseline_time_indices));
    times(2) = mean(S.times_in(time_indices));
else
    times(1) = mean(S.times_in(time_indices));
    conn=zeros(size(S.dat,1),1);
end;

for tri=1:size(S.dat,1), % indexes trials
    
    signal_h = hilbert(S.dat_seed(tri,:));

    % square the hilbert transform and take the
    % +ve square root to get the estimated envelope
    dat_seed = signal_h;
    
    signal_h = hilbert(S.dat(tri,:));

    % square the hilbert transform and take the
    % +ve square root to get the estimated envelope
    dat = signal_h;
    
    % Phase-Locking Value (PLV) (lie between 0 for no phase-locking
    % across trials and 1 for perfect phase-locking)
    cs = abs(mean(exp(sqrt(-1)*angle(dat(time_indices)-dat_seed(time_indices))))); % Measuring Phase Synchrony in Brain Signals. Jean-Philippe Lachaux et al, HBM 1999
    
    if(sum(baseline_time_indices)>0),
        
        % baseline  
        cs_baseline = abs(mean(exp(sqrt(-1)*angle(dat(baseline_time_indices)-dat_seed(baseline_time_indices))))); 
        
        conn(tri,1)=cs_baseline;    
        
        if(S.bc)
            conn(tri,2)=cs-cs_baseline;
        else
            conn(tri,2)=cs;
        end;

    else
        conn(tri,1)=cs;        
    end;
    
       
end;

